const multer = require('@koa/multer')
const COS = require('cos-nodejs-sdk-v5')

const cos = new COS({
  SecretId: 'AKIDLXfbJn1zjETWNzNWQ5VfZFgrmRqysXx8',
  SecretKey: 'xf8ML5cv0pX0ECuOcbLp32lGVTBdqnTs'
})
const bucket = 'popop-1333907626'
const region = 'ap-beijing'

// 上传文件
const cosUpload = (filename, path) => {
  return cos.uploadFile({
    Bucket: bucket,
    Region: region,
    Key: 'diancan/' + filename,
    FilePath: path,
    SliceSize: 1024 * 1024 * 5,
  })
}

// 删除文件
const cosDelete = (filename) => {
  return cos.deleteObject({
    Bucket: bucket,
    Region: region,
    Key: 'diancan/' + filename,
  })
}

// 配置上传文件所在目录和更改文件名
const storage = multer.diskStorage({ // 磁盘存储引擎方法
  destination: function (req, file, cb) {
    cb(null, 'upload/image')
  },
  filename: function (req, file, cb) {
    let fileFormat = (file.originalname).split('.')
    let randomStr = Math.random().toString().slice(2, 5)
    let fileName = Date.now() + '-' + randomStr + '.' + fileFormat[fileFormat.length - 1]
    cb(null, fileName)
  }
})

const upload = multer({storage: storage})

module.exports = {upload, cosUpload, cosDelete}